//
//  FPRankViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPRankViewController.h"
#import "FPRankView.h"
#import "FPRankTableViewCell.h"
#import "FPRankModel.h"
#import "FPRankTopModel.h"
#import "FPmainTopViewModel.h"
#import "FPMovieDetailViewController.h"
@interface FPRankViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)FPRankView *rankView;
@property(nonatomic,strong)NSIndexPath *indexPath;
@property(nonatomic,strong)NSMutableArray *movieArray;
@property(nonatomic,strong)MBProgressHUD *HUD;
/**
 找到上一个点击的label
 */
@property(nonatomic)NSInteger perIndexPath;
@end

@implementation FPRankViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.backgroundColor = [UIColor purpleColor];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth , 20)];
    statusBarView.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:statusBarView];
    [self creatTableView];
    [self analysisListData];
    self.perIndexPath = -1;
}

- (FPRankView *)rankView
{
    if (!_rankView) {
        _rankView = [[FPRankView alloc]init];
    }
    return _rankView;
}

#pragma mark=========添加tableView
- (void)creatTableView
{
    UIView *view = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:view];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:UITableViewStyleGrouped];
   
    self.tableView.rowHeight = kImageH(190);
    self.tableView.delegate  = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    //添加头部view;
    self.rankView.frame = CGRectMake(0, 0, kScreenWidth, kImageH(60));
    self.rankView.backgroundColor = [UIColor lightGrayColor];
    self.rankView.alpha = 0.5;
    self.tableView.tableHeaderView = self.rankView;
   }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark==================解析列表数据
//网络判断
- (void)judgeNet
{
    if (![[FPNetWork shareInstance]rechability])
    {
        UIAlertView *aler = [[UIAlertView alloc]initWithTitle:nil message:@"无网络" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [aler show];
        return;
    }
   
}
- (NSMutableArray *)movieArray
{
    if (!_movieArray) {
        _movieArray = [[NSMutableArray alloc]init];
    }
    return _movieArray;
}
- (void)analysisListData
{
  
    [self judgeNet];
    //创建url对象
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.view bringSubviewToFront:_HUD];
    self.HUD.labelText = @"正在为你加载";
    NSURL *url = [NSURL URLWithString:self.topListURL];
    //创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1.0];
    //开启异步联接 用队列的形式进行一步请求数据
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil) return ;
    
        //请求的所有数据已经全部接受完成的时候 ,才会执行Block快里的方法 此时data就是我们请求下来的数据它会自动传回到这个参数上面
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
           NSDictionary *topListDic = dic[@"topList"];
        FPRankTopModel *topListModel = [FPRankTopModel fpRankTopModelWithDictionary:topListDic];
        self.rankView.titleName.text = topListModel.name;
        self.rankView.introLable.text = topListModel.summary;
        NSDictionary *ListArray = dic[@"movies"];
        for (NSDictionary *movieDic in ListArray) {
            FPRankModel *rankModel = [FPRankModel fpRankModelSetValueWithDictionary:movieDic];
            rankModel.IDstr = movieDic[@"id"];
            NSLog(@"========================%@",rankModel.IDstr);
            [self.movieArray addObject:rankModel];
        }
        [self.tableView reloadData];
        [self.HUD hide:YES afterDelay:1];
    }];

}
#pragma mark=====代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.movieArray.count;
}

//返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"_cell";
    [tableView registerClass:[FPRankTableViewCell class] forCellReuseIdentifier:cellIndentifier];
    FPRankTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    cell.numLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1 ];
    if (indexPath.row == 0)
    {
        cell.numLabel.backgroundColor = [UIColor redColor];
    }
    else if (indexPath.row == 1)
    {
        cell.numLabel.backgroundColor = [UIColor greenColor];
    }
    else if (indexPath.row == 2)
    {
        cell.numLabel.backgroundColor = [UIColor blueColor];

    }
    else
    {
        cell.numLabel.backgroundColor = [UIColor lightGrayColor];

    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [cell.introLabel addGestureRecognizer:tap];
      UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction2:)];
    FPRankModel *rankModel = self.movieArray[indexPath.row];
    if (rankModel.isSelect == YES)
    {
        
       [cell adjustSubviewsWithContent:rankModel];
    }
    else
    {
        cell.introLabel.height = kImageH(50);
        
    }
   [cell cellforModel:rankModel];
    [cell addGestureRecognizer:tap2];
  
    return cell;
}


#pragma mark ====给label添加点击事件
- (void)tapAction:(UIGestureRecognizer *)sender

{
    //获取点击的位置
    CGPoint location = [sender locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
      FPRankTableViewCell *cell = (FPRankTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    self.indexPath = indexPath;
    cell.tag = 200 + indexPath.row;
    FPRankModel *rankModel = self.movieArray[indexPath.row];

        if (rankModel.isSelect == NO)
        {
            
        [cell adjustSubviewsWithContent:rankModel];
        }
    else
        {
        cell.introLabel.height = kImageH(50);
        
        }
        rankModel.isSelect = !rankModel.isSelect;

        [self.tableView reloadData];
}
#pragma mark ====给cell添加点击事件
- (void)tapAction2:(UIGestureRecognizer *)sender

{
    FPMovieDetailViewController *movieDetialVc = [[FPMovieDetailViewController alloc]init];
    FPmainTopViewModel *mainTopModel  = [[FPmainTopViewModel alloc]init];
    FPRankTableViewCell *cell = (FPRankTableViewCell *)sender.view;

    NSInteger row = [self.tableView indexPathForCell:cell].row;
    //   CGPoint location = [sender locationInView:self.tableView];
 //   NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
    FPRankModel *rankModel = self.movieArray[row];
    cell.introLabel.text = rankModel.remark;

    mainTopModel.imgstr = rankModel.posterUrl;
    cell.scoreLabel.text = [NSString stringWithFormat:@"%.1f",rankModel.rating] ;
    mainTopModel.ratingFinal = cell.scoreLabel.text;
     mainTopModel.titleCn = rankModel.name;
    cell.EnglishNameLabel.text = rankModel.nameEn;
    mainTopModel.titleEn = rankModel.nameEn;
      mainTopModel.directorName = rankModel.director;
      mainTopModel.actor1 = rankModel.actor;
    mainTopModel.movieID = [NSString stringWithFormat:@"%@",rankModel.IDstr];
    mainTopModel.time = rankModel.releaseDate;
       movieDetialVc.viewModel = mainTopModel;
    
    movieDetialVc.viewModel.isPass = YES;
    
    [self.navigationController pushViewController:movieDetialVc animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    FPRankModel *rankModel = self.movieArray[self.indexPath.row];
    if ( _perIndexPath != -1 && _indexPath.row != _perIndexPath)
    {
    
        FPRankModel *rankModel2 = self.movieArray[_perIndexPath];
        rankModel2.isSelect = NO;
        ((FPRankTableViewCell * )[self.view viewWithTag:200 + _perIndexPath]).introLabel.height = kImageH(50);
    }
    if (rankModel.isSelect == YES && indexPath.row == _indexPath.row)
    {
        self.perIndexPath = _indexPath.row;
        NSLog(@"%ld",_indexPath.row);
        return [FPRankTableViewCell heightForCell:rankModel];
    }
    else
    {  
       return kImageH(190);
    }

   
 }

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   // [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.backgroundColor = [UIColor purpleColor];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth , 20)];
    statusBarView.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:statusBarView];
}
@end
